package cn.net.chenbao.medical;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.OptionsPickerView;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.net.chenbao.medical.api.Api;
import cn.net.chenbao.medical.base.BaseActivity;
import cn.net.chenbao.medical.bean.Ks;
import cn.net.chenbao.medical.bean.User;
import cn.net.chenbao.medical.util.Consts;
import cn.net.chenbao.medical.util.ZLog;
import cn.net.chenbao.medical.xutils.ParamsUtils;
import cn.net.chenbao.medical.util.WWToast;
import cn.net.chenbao.medical.xutils.WWXCallBack;

public class LoginActivity extends BaseActivity implements TextWatcher {
    private EditText mEtAccount, mEtPwd;
    private String mAccountText, mPwdText;
    private TextView mTvDeviceId, mTvSure;

    private OptionsPickerView mKsPv;
    private User mUser;
    private List<Ks> mKsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(Api.WW_ONLINE)) {
            WWToast.showShort(R.string.please_input_host);
            startActivity(new Intent(LoginActivity.this, EditHostActivity.class));
        }
        //自动登录
        if (MedicalApplication.getInstance().isLogin()) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    private void initData() {
        //获取当前设备号（deviceId）
        String deviceId = getResources().getString(R.string.device_number) + ":" + MedicalApplication.getInstance().getDeviceId();
        ZLog.e(deviceId);
        mTvDeviceId.setText(deviceId);
    }

    private void initView() {
        findViewById(R.id.view_host_address).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, EditHostActivity.class));
            }
        });
        mTvDeviceId = (TextView) findViewById(R.id.tv_device_number);
        mEtAccount = (EditText) findViewById(R.id.et_account);
        mEtPwd = (EditText) findViewById(R.id.et_password);
        mEtAccount.addTextChangedListener(this);
        mEtPwd.addTextChangedListener(this);
        mTvSure = (TextView) findViewById(R.id.tv_login);
        mTvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (event.getKeyCode()) {
            case 19:
                //上
                if (mKsPv != null && mKsPv.isShowing()) {
                    mKsPv.SetOption1CurrentItemPre(mKsList.size());
                    break;
                }
                break;
            case 20:
                //下
                if (mKsPv != null && mKsPv.isShowing()) {
                    mKsPv.SetOption1CurrentItemNext(mKsList.size());
                    break;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //这里注意要作判断处理，ActionDown、ActionUp都会回调到这里，不作处理的话就会调用两次
        if (KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction()) {
            //处理事件
            if (mKsPv != null && mKsPv.isShowing()) {
                mKsPv.returnData();
                mKsPv.dismiss();
                return true;
            }
            login();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private void login() {
        if (TextUtils.isEmpty(mAccountText)) {
            WWToast.showShort(R.string.please_input_account);
            return;
        }
        if (TextUtils.isEmpty(mPwdText)) {
            WWToast.showShort(R.string.please_input_password);
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put(Consts.DEVICE_ID, MedicalApplication.getInstance().getDeviceId());
        jsonObject.put(Consts.USER_ID, mAccountText);
        jsonObject.put(Consts.PASSWORD, mPwdText);
        mTvSure.setClickable(false);
        x.http().post(
                ParamsUtils.getPostJsonParams(jsonObject, Api.login()),
                new WWXCallBack("Login") {

                    @Override
                    public void onAfterSuccessOk(JSONObject data) {
                        mUser = JSON.parseObject(data.getString("Data"), User.class);
                        mKsList = JSON.parseArray(data.getString("KsInfo"), Ks.class);
                        if (mUser == null)
                            return;
                        if (mKsList == null || mKsList.size() <= 1) {
                            MedicalApplication.getInstance().setSessionId(mUser.SessionId.trim());
                            MedicalApplication.getInstance().setOperName(mUser.OperName.trim());
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        } else {
                            ShowKsPv(mKsList);
                        }
                    }

                    @Override
                    public void onAfterSuccessError(JSONObject data) {
                        super.onAfterSuccessError(data);

                    }

                    @Override
                    public void onAfterFinished() {
                        mTvSure.setClickable(true);
                    }
                });
    }

    public void LoginKsSubmit(String no) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(Consts.SESSION_ID, mUser.SessionId.trim());
        jsonObject.put("ksNo", no);
        mTvSure.setClickable(false);
        x.http().post(
                ParamsUtils.getPostJsonParams(jsonObject, Api.LoginKsSubmit()),
                new WWXCallBack("LoginKsSubmit") {

                    @Override
                    public void onAfterSuccessOk(JSONObject data) {
                        MedicalApplication.getInstance().setSessionId(mUser.SessionId.trim());
                        MedicalApplication.getInstance().setOperName(mUser.OperName.trim());
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onAfterFinished() {
                        mTvSure.setClickable(true);
                    }
                });
    }

    public void ShowKsPv(final List<Ks> datas) {
        mKsPv = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                LoginKsSubmit(datas.get(options1).No);
            }
        })
                .setDividerColor(ContextCompat.getColor(this, R.color.main_line_color))
                .setTextColorCenter(ContextCompat.getColor(this, R.color.main_color)) //设置选中项文字颜色
                .setTextColorOut(ContextCompat.getColor(this, R.color.black2))
                .setCancelColor(ContextCompat.getColor(this, R.color.black))
                .setSubmitColor(ContextCompat.getColor(this, R.color.main_color))
                .setTitleText("选择科室（必选）")
                .setTitleSize(13)
                .setTitleBgColor(ContextCompat.getColor(this, R.color.white))
                .setBgColor(ContextCompat.getColor(this, R.color.white))
                .setContentTextSize(16)
                .setSubCalSize(16)
                .build();
        mKsPv.setPicker(datas);
        mKsPv.show();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mAccountText = mEtAccount.getText().toString().trim();
        mPwdText = mEtPwd.getText().toString().trim();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
